package com.zzzyh.forumsystemclient.services.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzzyh.forumsystemclient.dao.*;
import com.zzzyh.forumsystemclient.model.*;
import com.zzzyh.forumsystemclient.services.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Article> list(Integer pageNum, Integer pageSize) {
        List<Article> articlesTop = new ArrayList<>();
        if (pageNum == 1){
         articlesTop = articleMapper.listTop();
        }
        List<Article> articles = articleMapper.list((pageNum - 1) * pageSize, pageSize);
        articlesTop.addAll(articles);
        for (Article article : articlesTop){
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setTags(tagMapper.getTagsByArticleId(article.getId()));
            if (article.getCategoryId() != null){
                // 修复空指针异常：先获取Category对象，再判断是否为null
                Category category = categoryMapper.selectByPrimaryKey(article.getCategoryId());
                if (category != null) {
                    article.setCategoryName(category.getName());
                } else {
                    article.setCategoryName("未知分类");
                }
            }
        }
        return articlesTop;
    }

    @Override
    public Integer total() {
        return articleMapper.total();
    }

    @Override
    public List<Article> getCarousels() {
        return articleMapper.getCarousels();
    }

    @Override
    public List<Article> getRecommends() {
        return articleMapper.getRecommends();
    }

    @Override
    public Article getByArticleId(Long articleId) {
        Article article = articleMapper.getByArticleId(articleId);
        if (article == null){
            return null;
        }
        User user = userMapper.selectByPrimaryKey(article.getUserId());
        article.setNickname(user.getNickname());
        article.setAvatar(user.getAvatar());
        article.setTags(tagMapper.getTagsByArticleId(article.getId()));
        Category category = categoryMapper.selectByPrimaryKey(article.getCategoryId());
        // 修复空指针异常：检查category是否为null
        if (category != null) {
            article.setCategoryName(category.getName());
            article.setCategory(category);
        } else {
            article.setCategoryName("未知分类"); // 设置默认分类名称
            article.setCategory(null);
        }
        return article;
    }

    @Override
    public List<ArchiveResponse> getArchivedArticles() {
        List<Article> articles = articleMapper.getAllArticles();
        // 按年份分组
        Map<Integer, List<Article>> archiveMap = new HashMap<>();
        for (Article article : articles) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(article.getCreateTime());
            int year = cal.get(Calendar.YEAR);
            archiveMap.computeIfAbsent(year, k -> new ArrayList<>()).add(article);
        }

        // 转换为 ArchiveResponse 列表
        List<ArchiveResponse> result = new ArrayList<>();
        for (Map.Entry<Integer, List<Article>> entry : archiveMap.entrySet()) {
            result.add(new ArchiveResponse(entry.getKey(), entry.getValue()));
        }

        // 按年份降序排列
        result.sort((r1, r2) -> Integer.compare(r2.getYear(), r1.getYear()));
        return result;
    }

    @Override
    public List<CategoryPostResponse> getCategoryWithArticles() {
        List<Category> categories = categoryMapper.categorieAll(); // 获取所有分类
        List<CategoryPostResponse> result = new ArrayList<>();

        for (Category category : categories) {
            List<Article> articles = articleMapper.getArticlesByCategoryId(category.getId()); // 根据分类ID查询文章
            result.add(new CategoryPostResponse(category.getId(), category.getName(), articles));
        }

        return result;
    }

    @Override
    public List<Article> getArticlesByTagId(Integer tagId, Integer pageNum, Integer pageSize) {
        List<Article> articlesTop = articleMapper.getArticlesTopByTagId(tagId);
        log.info("articlesTop: {}", articlesTop);
        List<Article> articles = articleMapper.getArticlesByTagId(tagId,(pageNum - 1) * pageSize, pageSize);
        log.info("articles: {}", articles);
        articlesTop.addAll(articles);
        for (Article article : articlesTop){
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setTags(tagMapper.getTagsByArticleId(article.getId()));
            if (article.getCategoryId() != null){
                // 修复空指针异常
                Category category = categoryMapper.selectByPrimaryKey(article.getCategoryId());
                if (category != null) {
                    article.setCategoryName(category.getName());
                } else {
                    article.setCategoryName("未知分类");
                }
            }
        }
        return articlesTop;
    }

    @Override
    public Integer totalByTagId(Integer tagId) {
        return articleMapper.totalByTagId(tagId);
    }

    @Override
    public Integer totalByCategoryId(Integer categoryId) {
        return articleMapper.totalByCategoryId(categoryId);
    }

    @Override
    public List<Article> getArticlesByCategoryId(Integer categoryId, Integer pageNum, Integer pageSize) {
        List<Article> articlesTopByCategoryId = articleMapper.getArticlesTopByCategoryId(categoryId);
        List<Article> articlesByCategoryIdByPage = articleMapper.getArticlesByCategoryIdByPage(categoryId, (pageNum - 1) * pageSize, pageSize);
        articlesTopByCategoryId.addAll(articlesByCategoryIdByPage);
        for (Article article : articlesTopByCategoryId){
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setTags(tagMapper.getTagsByArticleId(article.getId()));
            article.setCategoryName(categoryMapper.selectByPrimaryKey(article.getCategoryId()).getName());
        }
        return articlesTopByCategoryId;
    }

    @Override
    public List<Article> getArticlesByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        return articleMapper.getArticlesByUserId(userId,(pageNum - 1) * pageSize, pageSize);
    }

    @Override
    public Integer totalByUserId(Integer userId) {
        return articleMapper.totalByUserId(userId);
    }

    @Override
    public List<Article> getMyLike(Integer pageNum, Integer pageSize, Integer userId) {
        return articleMapper.getMyLike((pageNum-1)*pageSize, pageSize, userId);
    }

    @Override
    public Integer getMyLikeTotal(Integer id) {
        return articleMapper.getMyLikeTotal(id);
    }

    @Override
    public void like(Long articleId, Integer userId) {
        articleMapper.like(articleId,userId);
    }

    @Override
    public Integer isLike(Long articleId, Integer userId) {
        return articleMapper.isLike(articleId,userId);
    }

    @Override
    public void unlike(Long articleId, Integer userId) {
        articleMapper.unlike(articleId,userId);
    }

    @Override
    public Integer getArticleLikeTotal(Long articleId) {
        return articleMapper.getArticleLikeTotal(articleId);
    }

    @Override
    public void add(Article article) {
        articleMapper.add(article);
    }

    @Override
    public List<Article> getArticlesByKeyword(String keyword, Integer pageNum, Integer pageSize,Integer userId) {
        List<Article> articlesByKeyword = articleMapper.getArticlesByKeyword(keyword, (pageNum - 1) * pageSize, pageSize);
        List<User> users = userMapper.getUserInfoByKeyword(keyword);

        for (Article article : articlesByKeyword){
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setTags(tagMapper.getTagsByArticleId(article.getId()));
            article.setCategoryName(categoryMapper.selectByPrimaryKey(article.getCategoryId()).getName());
            article.setUserName(user.getUsername());
            article.setIsUserInfo(0);
        }
        for (User user:
                users) {
            Article article = new Article();
            article.setContent(user.getSignature());
            article.setId(-1L);
            article.setUserName(user.getUsername());
            article.setIsUserInfo(1);
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setUserId(user.getId());
            articlesByKeyword.add(0,article);
            Integer like = userMapper.isFollowAuthor(userId, user.getId());
//            log.info("{}like{}: {}",userId,like,user.getId());
            article.setIsFollowAuthor(like!= null?like:0);
        }
        return articlesByKeyword;
    }

    @Override
    public Integer totalByKeyword(String keyword) {
        return articleMapper.totalByKeyword(keyword);
    }

    @Override
    public List<Article> getArticlesByTitle(String title, Integer userId, Integer pageNum, Integer pageSize) {
        List<Article> articlesByTitle = articleMapper.getArticlesByTitle(title, userId, (pageNum - 1) * pageSize, pageSize);
        for (Article article : articlesByTitle){
            User user = userMapper.selectByPrimaryKey(article.getUserId());
            article.setNickname(user.getNickname());
            article.setAvatar(user.getAvatar());
            article.setTags(tagMapper.getTagsByArticleId(article.getId()));
            article.setCategoryName(categoryMapper.selectByPrimaryKey(article.getCategoryId()).getName());
        }
        return articlesByTitle;
    }

    @Override
    public Integer totalByTitle(String title, Integer userId) {
        return articleMapper.totalByTitle(title,userId);
    }

    @Override
    public void addArticleQuantity(Long articleId) {
        articleMapper.addArticleQuantity(articleId);
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

    @Override
    public void delete(Long articleId) {
        articleMapper.delete(articleId);
    }


}
